package com.newland.mesdk.demo.fragment;

import java.util.Random;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.DeviceInfo;
import com.newland.mtype.module.common.security.AuthDataMode;
import com.newland.mtype.module.common.security.AuthenticationResult;
import com.newland.mtype.module.common.security.AuthenticationType;
import com.newland.mtype.module.common.security.CertifiedModel;
import com.newland.mtype.util.Dump;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.interfaceimpl.SecurityInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.SharedPreferencesUtil;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF 设备安全认证模块
 */
public class SecurityFragment extends Fragment implements OnClickListener {
	private MainActivity mainActivity;
	private String connectType;
	private String deviceType;
	private SecurityInterfaceImpl securityInterfaceImpl;
	private Button btnGetMess, btnGetRadom, btnDeviceSecurity;
	private Button btnAuthentication, btnGenerateAsymmetriData;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_security, null);
		mainActivity = (MainActivity) getActivity();
		connectType = SharedPreferencesUtil.getStringParam(mainActivity, Const.CONNECTTYPE);
		deviceType = SharedPreferencesUtil.getStringParam(mainActivity, Const.DEVICETYPE);
		initSecurityView(view);
		return view;
	}

	public void initSecurityView(View view) {
		btnGetMess = (Button) view.findViewById(R.id.btn_secutity_getmess);
		btnGetMess.setOnClickListener(this);

		btnGetRadom = (Button) view.findViewById(R.id.btn_security_getradon);
		btnGetRadom.setOnClickListener(this);

		btnDeviceSecurity = (Button) view.findViewById(R.id.btn_security_device_security);
		btnDeviceSecurity.setOnClickListener(this);

		btnAuthentication = (Button) view.findViewById(R.id.btn_security_authentication);
		btnAuthentication.setOnClickListener(this);

		btnGenerateAsymmetriData = (Button) view.findViewById(R.id.btn_security_generate_asymmetricdata);
		btnGenerateAsymmetriData.setOnClickListener(this);

		if (deviceType.equals(Const.DeviceName.IM81)) {
			btnAuthentication.setVisibility(View.GONE);
			btnGenerateAsymmetriData.setVisibility(View.GONE);
		} else if (deviceType.equals(Const.DeviceName.AUDIO)) {
			btnAuthentication.setVisibility(View.GONE);
			btnGenerateAsymmetriData.setVisibility(View.GONE);
		}  else if(deviceType.equals(Const.DeviceName.N900)){
			btnAuthentication.setVisibility(View.GONE);
			btnGenerateAsymmetriData.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			if (mainActivity.processingisLocked()) {
				mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
			} else {
				mainActivity.connectDevice();
				securityInterfaceImpl = new SecurityInterfaceImpl();
				switch (v.getId()) {
				case R.id.btn_secutity_getmess:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("开始获取设备信息... " + "\r\n", MessageTag.NORMAL);
								DeviceInfo deviceInfo;
								if (connectType.equals("Audio")) {
									deviceInfo = securityInterfaceImpl.getDeviceInfoByAudio();
								} else {
									deviceInfo = securityInterfaceImpl.getDeviceInfo();
								}
								mainActivity.showMessage("设备CSN号:" + deviceInfo.getCSN() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("设备KSN号:" + deviceInfo.getKSN() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("设备应用版本号:" + deviceInfo.getAppVer() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("设备Boot版本号:" + deviceInfo.getBootVersion() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备类型:" + deviceInfo.getPID() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("设备SN号:" + deviceInfo.getSN() + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("设备是否支持音频:" + deviceInfo.isSupportAudio() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持蓝牙:" + deviceInfo.isSupportBlueTooth() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持接触式IC卡:" + deviceInfo.isSupportICCard() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持屏幕显示:" + deviceInfo.isSupportLCD() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持磁条卡:" + deviceInfo.isSupportMagCard() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持脱机交易:" + deviceInfo.isSupportOffLine() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持打印:" + deviceInfo.isSupportPrint() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持非接触IC卡:" + deviceInfo.isSupportQuickPass() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否支持USB:" + deviceInfo.isSupportUSB() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备默认初始状态:" + deviceInfo.isFactoryModel() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否安装主密钥:" + deviceInfo.isMainkeyLoaded() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否安装工作密钥:" + deviceInfo.isWorkingkeyLoaded() + "\r\n",
										MessageTag.DATA);
								mainActivity.showMessage("设备是否安装dukpt密钥:" + deviceInfo.isDUKPTkeyLoaded() + "\r\n",
										MessageTag.DATA);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("获取设备信息 异常 " + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_security_device_security:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("开始设备认证... " + "\r\n", MessageTag.NORMAL);
								byte[] radom1 = getRandomByte(8);
								mainActivity.showMessage("随机数 结果:" + Dump.getHexDump(radom1) + "\r\n", MessageTag.DATA);
								String deviceIdentify = securityInterfaceImpl.deviceIdentify(CertifiedModel.SYMMETRIC,
										radom1);
								mainActivity.showMessage("设备认证 结果:" + deviceIdentify + "\r\n", MessageTag.DATA);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("设备认证 异常 " + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_security_getradon:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								byte[] radom = securityInterfaceImpl.getSecurityRandom();
								mainActivity.showMessage("获得一个线路保护的随机数为：" +  Dump.getHexDump(radom) + "\r\n", MessageTag.DATA);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("获得一个线路保护的随机数 异常 " + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_security_authentication:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								mainActivity.showMessage("开始双向对称认证... " + "\r\n", MessageTag.NORMAL);
								byte[] randomNum = getRandomByte(8);
								byte[] workKey = ISOUtils.hex2byte("D2CEEE5C1D3AFBAF00374E0CC1526C86");
								byte[] authData = getRandomByte(8);
								AuthenticationResult authenticationResult1 = securityInterfaceImpl
										.bidirectionalAuthentication(AuthenticationType.MAKE_DATA,
												AuthDataMode.ECB_TDES, 1, 1, workKey, authData, randomNum);
								byte[] checkValue1 = authenticationResult1.getCheckValue();
								AuthenticationResult.ResultCode resultCode1 = authenticationResult1.getResultCode();
								byte[] resultData1 = authenticationResult1.getResultData();
								if (checkValue1 != null) {
									mainActivity.showMessage("双向对称认证的checkvalue=:" + Dump.getHexDump(checkValue1)
											+ "\r\n", MessageTag.DATA);
								}
								if (resultCode1 != null) {
									mainActivity.showMessage("双向对称认证的resultCode=:" + resultCode1 + "\r\n",
											MessageTag.DATA);
								}
								if (resultData1 != null) {
									mainActivity.showMessage("双向对称认证的resultData=:" + Dump.getHexDump(resultData1)
											+ "\r\n", MessageTag.DATA);
								}
								mainActivity.showMessage("双向对称认证成功! " + "\r\n", MessageTag.NORMAL);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("双向对称认证 异常 " + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_security_generate_asymmetricdata:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								AuthenticationResult authenticationResult = securityInterfaceImpl
										.generateAsymmetricData(1, 8, 1);
								byte[] checkValue = authenticationResult.getCheckValue();
								AuthenticationResult.ResultCode resultCode = authenticationResult.getResultCode();
								byte[] resultData = authenticationResult.getResultData();
								mainActivity.showMessage("非对称认证数据的checkvalue=:" + Dump.getHexDump(checkValue)
										+ "\r\n", MessageTag.DATA);
								mainActivity.showMessage("非对称认证数据的resultCode=:" + resultCode + "\r\n", MessageTag.DATA);
								mainActivity.showMessage("非对称认证数据的resultData=:" + Dump.getHexDump(resultData)
										+ "\r\n", MessageTag.DATA);
								mainActivity.processingUnLock();

							} catch (Exception e) {
								mainActivity.showMessage("产生非对称认证数据 异常 " + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;

				default:
					break;
				}
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.NORMAL);
		}
	}

	// 获取随机数
	public static byte[] getRandomByte(int length) {

		byte[] random = new byte[length];
		Random randomInt = new Random();
		for (byte by : random) {
			int b1 = randomInt.nextInt(256);
			by = (byte) (b1);
			System.out.println(by + "," + b1);
		}

		return random;
	}

}
